package com.sie.zhq.module;

import android.os.SystemClock;
import android.util.Log;

import com.sie.zhq.constconfig.ConstDefine;
import com.sie.zhq.tool.Timer;

import java.io.IOException;

/**
 * Created by zhq on 2017/7/4.
 */

public class ScanModule extends SerialPortModule {

    public final static String TAG = "FinancialModule";
    private static ScanModule ourInstance = new ScanModule();


    public static ScanModule getInstance() {
        return ourInstance;
    }

    private String serialDev = ConstDefine.SCAN_PORT;
    private int baudRate = 115200;
    protected boolean isOpen = false;

    public ScanModule(){

         boolean init = initSerialPort(serialDev,baudRate);
         Log.e("scanModule init",init+"---");
    }

    public  int openScan(byte[] result){
        byte[] cmd = {0x1A, 0x54, 0x0D};
        this.writeFlush(cmd, cmd.length);

        int res = 0;
        try {
            res = receiveUntilStop(result, (byte) 0x0d,30000);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;

    }

    public synchronized int receiveUntilStop(byte[] rspMsg,byte stopFlag, int timeOutMs) throws IOException {
        int reveiveLen = 0;
        int availabelLen = 0;
        int readLenPerTime = 0;
        Timer tm = null;
        if (rspMsg == null) {

            return -1;
        }
        if (timeOutMs > 0) {
            tm = new Timer(timeOutMs);
            tm.start();

        }
        while (true) {
            if (timeOutMs > 0) {
                if (tm.timeOut()) {
                    Log.e(TAG, "tm.timeOut!!");
                    break;
                }
            }
            availabelLen = mInputStream.available();

            if (availabelLen > 0) {
                readLenPerTime = mInputStream.read(rspMsg, reveiveLen, 1);
                reveiveLen += readLenPerTime;
                //Log.e("repmsg:"+reveiveLen, ByteTool.byte2hex(rspMsg,0,reveiveLen,true));
                if(rspMsg[reveiveLen-1]==stopFlag){
                    Log.e("reveiveLen","stop");
                    break;
                }
            }
            SystemClock.sleep(1);
        }
        return reveiveLen;
    }






}
